<template>
  <div class="music">
    <!-- <audio ref="audioRef" autoplay>
      <source :src="data.src" type="audio/mp3">
    </audio> -->
    <div class="player" ref="playerRef">
      <div class="top" style="display: flex;justify-content: space-between;">
        <div>{{ data.fileName }}</div>
        <div>{{ data.cur + '/' + data.dur }}</div>
      </div>
      <div class="progress" @click="selectProgress($event)" @mouseover="hoverProgress($event)" :title="data.time">
        <div class="line" :style="{ width: data.progress + '%' }"></div>
      </div>
      <ul>
        <li @click="last"><span class="iconfont icon-shangyishou"></span></li>
        <li @click="huitui"><span class="iconfont icon-rewkuaitui"></span></li>
        <li @click="play">
          <span class="iconfont icon-ai07" v-if="musicSet.playing"></span>
          <span class="iconfont icon-bofang11" v-else></span>
        </li>
        <li @click="kuaijin"><span class="iconfont icon-speedkuaijin"></span></li>
        <li @click="next"><span class="iconfont icon-xiayishou"></span></li>
        <li @click="selectMode">
          <span class="iconfont icon-liebiaoxunhuan" v-if="musicSet.mode == 1"></span>
          <span class="iconfont icon-danquxunhuan" v-else-if="musicSet.mode == 2"></span>
          <span class="iconfont icon-repeat" v-else></span>
        </li>
        <li @click="showSet" :class="showOption.isSet ? 'selected' : ''"><span class="iconfont icon-gongju"></span>
        </li>
        <li @click="showList" :class="showOption.isList ? 'selected' : ''"><span class="iconfont icon-gedan"></span>
        </li>
      </ul>
      <div class="isSet" v-if="showOption.isSet">
        <div class="list-con">
          <div>
            <div v-for="(x, y) in files" :key="y" @click="selectFile(y)" :class="y == data.fileIdx ? 'active' : ''">
              {{ x }}
            </div>
          </div>
          <div>
            <div v-for="(x, y) in speeds" :key="y" @click="selectSpeed(y)"
              :class="y == musicSet.speedIdx ? 'active' : ''">
              {{ x }}
            </div>
          </div>
        </div>
        <div class="voice-con">
          <div class="voice-icon" @click="fullVoice">
            <span class="iconfont icon-jingyin" v-if="data.notVoice"></span>
            <span class="iconfont icon-sound" v-else></span>
          </div>
          <div class="voice-progress" @click="selectVoice($event)">
            <div class="voice-line" :style="{ width: musicSet.voice + '%' }"></div>
          </div>
          <div class="voice-icon" @click="downVoice">
            <span class="iconfont icon-suoxiao"></span>
          </div>
          <div class="voice-icon" @click="upVoice">
            <span class="iconfont icon-jia"></span>
          </div>
        </div>
      </div>
      <div class="isList" v-if="showOption.isList">
        <div class="type">
          <div v-for="(x, y) in data.musicTpyes" :key="y" @click="selecType(y)"
            :class="y == musicSet.typeIdx ? 'selected' : ''">
            {{
              x }}
          </div>
        </div>
        <div class="list">
          <div v-for="(x, y) in data.musicList" :key="y" @click="selectMusic(y)"
            :class="y == musicSet.listIdx ? 'active' : ''">
            {{ x }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from 'vue'
import system from '@/utils/system';
import global from '@/utils/global';
import { queryData } from '@/apis/mysql';
import { MusicSetStore } from '@/stores/index.js'
const useMusicSetStore = MusicSetStore()
const speeds = [0.1, 0.5, 1, 2, 5]
const files = ['musics', 'songs']
const audioRef = ref(null)
const playerRef = ref(null)
let url = ''
const data = reactive({
  musicTpyes: [],
  musicList: [],
  fileName: '',
  src: '',
  cur: '',
  dur: '',
  time: '',
  fileIdx: 0,
  notVoice: false,
  progress: 0
})

// 显示
const showOption = reactive({
  isList: false,
  isSet: false
})

// 播放器设置，可保存状态
const musicSet = reactive({
  listIdx: 0,
  typeIdx: 0,
  playing: false,
  voice: 40,
  mode: 1,
  speedIdx: 2
})
const { MusicSet } = useMusicSetStore
watch(
  () => MusicSet.playing,
  (name) => {
    console.log(name)
  }
)

watch(
  () => MusicSet.listIdx,
  (idx) => {
    console.log(idx)
  }
)

onMounted(() => {
  getPath()
  // if (audioRef.value) {
  //   listen()
  // }
})

function getPath() {
  queryData({
    table: 'resources',
    data: {
      name: 'musics'
    }
  }).then((res) => {
    let obj = res.data[0]
    url = `${obj.disk}:/${obj.path}`
    musicSetting().then(() => {
      getMusicTypes()
    })
  })
}

function getMusicTypes() {
  let path = url + '/' + files[data.fileIdx]
  system.readDir(path).then(res => {
    data.musicTpyes = res
    getList()
  })
}

function musicSetting() {
  return new Promise((resolve) => {
    const { MusicSet } = useMusicSetStore
    for (let i in MusicSet) {
      musicSet[i] = MusicSet[i]
    }
    resolve()
  })
}

function getList() {
  let path = url + '/' + files[data.fileIdx]
  system.readDir(path + '/' + data.musicTpyes[musicSet.typeIdx]).then(res => {
    const arr = []
    res.map(x => {
      if (x.includes('.mp3')) {
        arr.push(x)
      }
    })
    data.musicList = arr
    if (musicSet.playing) {
      selectMusic(musicSet.listIdx)
    }
  })
}

function selecType(y) {
  musicSet.typeIdx = y
  musicSet.listIdx = 0
  getList()
}

function selectMusic(y) {
  musicSet.listIdx = y
  replay()
}

function replay() {
  let path = url + '/' + files[data.fileIdx]
  musicSet.playing = true
  data.fileName = data.musicList[musicSet.listIdx]
  data.src = path + '/' + data.musicTpyes[musicSet.typeIdx] + '/' + data.musicList[musicSet.listIdx]
  // setTimeout(() => {
  //   audioRef.value.load();
  //   audioRef.value.volume = musicSet.voice / 100
  //   audioRef.value.playbackRate = speeds[musicSet.speedIdx]
  // }, 100)
  saveMusicSet('typeIdx', musicSet.typeIdx)
  saveMusicSet('listIdx', musicSet.listIdx)
  saveMusicSet('playing', true)
  saveMusicSet('src', data.src)
}

function listen() {
  audioRef.value.addEventListener('timeupdate', () => {
    let cur = audioRef.value.currentTime
    let dur = audioRef.value.duration
    data.cur = global.formatTime(cur)
    data.dur = global.formatTime(dur)
    data.progress = cur / dur * 100
    if (cur == dur) {
      playMode()
    }
  })
}

function showBtn(str){
  showOption[str] = !showOption[str]
}

function showList() {
  showBtn('isList')
}

function showSet() {
  showBtn('isSet')
  // showOption.isSet = !showOption.isSet
}

function saveMusicSet(attr, value) {
  let obj = useMusicSetStore.MusicSet ? useMusicSetStore.MusicSet : {}
  obj[attr] = value
  useMusicSetStore.setMusicSet(obj)
}

function play() {
  if (musicSet.playing) {
    musicSet.playing = false
    saveMusicSet('playing', false)
    audioRef.value.pause()
  } else {
    musicSet.playing = true
    saveMusicSet('playing', true)
    audioRef.value.play()
  }
}

function next() {
  musicSet.listIdx += 1
  if (musicSet.listIdx > data.musicList.length - 1) {
    musicSet.listIdx = 0
  }
  replay()
}

function last() {
  musicSet.listIdx -= 1
  if (musicSet.listIdx < 0) {
    musicSet.listIdx = data.musicList.length - 1
  }
  replay()
}

// function selectProgress(e) {
//   const scale = e.offsetX * 100 / (playerRef.value.offsetWidth - 20)
//   audioRef.value.currentTime = scale * audioRef.value.duration / 100
// }

// function hoverProgress(e) {
//   const scale = e.offsetX * 100 / (playerRef.value.offsetWidth - 20)
//   const cur = audioRef.value.duration * scale / 100
//   data.time = global.formatTime(cur)
// }

function selectVoice(e) {
  const scale = e.offsetX * 100 / 150
  musicSet.voice = scale
  audioRef.value.volume = scale / 100
  saveMusicSet('voice', musicSet.voice)
}

function selectSpeed(y) {
  musicSet.speedIdx = y
  audioRef.value.playbackRate = speeds[y]
  saveMusicSet('speedIdx', y)
}

function selectFile(y) {
  data.fileIdx = y
  getMusicTypes()
}

function fullVoice() {
  data.notVoice = !data.notVoice
  if (data.notVoice) {
    musicSet.voice = 0
    audioRef.value.volume = 0
  } else {
    musicSet.voice = 100
    audioRef.value.volume = 1
  }
  saveMusicSet('voice', musicSet.voice)
}

function upVoice() {
  if (musicSet.voice <= 90) {
    musicSet.voice += 10
  } else {
    musicSet.voice = 100
    data.notVoice = false
  }
  audioRef.value.volume = musicSet.voice / 100
  saveMusicSet('voice', musicSet.voice)
}


function downVoice() {
  if (musicSet.voice >= 10) {
    musicSet.voice -= 10
  } else {
    musicSet.voice = 0
    data.notVoice = true
  }
  audioRef.value.volume = musicSet.voice / 100
  saveMusicSet('voice', musicSet.voice)
}

function selectMode() {
  if (musicSet.mode < 3) {
    musicSet.mode++
  } else {
    musicSet.mode = 1
  }
  saveMusicSet('mode', musicSet.mode)
}

function playMode() {
  switch (musicSet.mode) {
    case 1:
      next()
      break;
    case 2:
      replay()
      break;
    case 3:
      musicSet.listIdx = parseInt(Math.random() * data.musicList.length)
      replay()
      break;
  }
}

function kuaijin() {
  audioRef.value.currentTime += 10
}

function huitui() {
  audioRef.value.currentTime -= 10
}

</script>
<style scoped lang="scss">
$color1: rgb(159, 5, 61);
$color2: #000;

.active {
  color: $color1;
}

.selected {
  background-color: $color1;
  color: #fff;
}

.music {
  user-select: none;

  .player {
    width: 100%;
    padding: 10px;
    box-shadow: inset 0 0 10px $color1;
    // background: #111;

    .progress {
      width: 100%;
      height: 4px;
      margin: 10px 0;
      background-color: #ccc;
      position: relative;
      cursor: pointer;

      .line {
        height: 4px;
        background-color: $color1;
        position: absolute;
      }
    }

    ul {
      display: flex;

      li {
        width: 40px;
        height: 40px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        margin: 0 5px;

        .iconfont {
          font-size: 24px;
        }
      }

      .selected {
        border-radius: 50%;
      }
    }

    .isSet {
      .voice-con {
        display: flex;
        width: 320px;
        height: 40px;

        .voice-icon {
          width: 40px;
          height: 40px;
          display: flex;
          justify-content: center;
          align-items: center;
          cursor: pointer;

          .iconfont {
            font-size: 24px;
          }
        }

        .voice-progress {
          width: 150px;
          height: 4px;
          margin-top: 18px;
          background-color: #ccc;
          position: relative;
          cursor: pointer;

          .voice-line {
            height: 4px;
            background-color: $color1;
            position: absolute;
          }
        }
      }

      .list-con {
        display: flex;
        width: 200px;
        height: 40px;

        >div {
          display: flex;

          >div {
            height: 40px;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            margin-right: 20px;
          }
        }
      }
    }
  }

  .isList {
    .type {
      display: flex;
      margin: 10px 0;

      >div {
        width: 12.5%;
        height: 30px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
      }
    }

    .list {
      width: 100%;
      height: 300px;
      overflow: auto;
      display: flex;
      flex-wrap: wrap;

      >div {
        width: 33%;
        margin-bottom: 10px;
        cursor: pointer;
      }
    }
  }
}
</style>
